<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<script th:inline="javascript">
function initNestSheetAutoSel[(${nestFormCode})]() {
		// 自动拉单功能
		var isAutoSel = [(${isAutoSel})];
		console.log('macro_js_nestsheet isAutoSel', isAutoSel);
		if (isAutoSel) {
		    //如果是自动嵌套拉单，每隔两秒执行检查是否该刷新表格
			var fields = [[${mainFormFieldNames}]];
			var fieldNames = fields.split(",");
            console.log('isAutoSel fields', fields, 'fieldNames', fieldNames);

			var fieldObj = o(fieldNames[0]);

			console.log('initNestSheetAutoSel cwsId', jQuery("[code='[(${nestFieldName})]']").attr('cwsId'));

			var oldValueArr = getFormValue(fieldNames);
			var ajaxData = {
				'flowId': [[${flowId}]],
				'parentFormCode': [[${parentFormCode}]],
				'parentId': jQuery("[code='[(${nestFieldName})]']").attr('cwsId'),
				'nestFieldName': [[${nestFieldName}]],
				'isFirst':true
			};
			// 当找不到元素时oldValueArr为null，有可能是发起流程然后切换选项卡太快时，就会找不到
			if (oldValueArr != null) {
				for (var i in fieldNames) {
					ajaxData[fieldNames[i]] = oldValueArr[i];
				}
			}
			// 如果获取到值的数组中有不为空的，则需立即自动拉单，否则不需要
			var isDoAutoSelImmediate = false;
			if (oldValueArr != null && oldValueArr.length > 0) {
				for (var m in oldValueArr) {
					if (oldValueArr[m]) {
						isDoAutoSelImmediate = true;
						break;
					}
				}
			}
			console.log('oldValueArr', oldValueArr, 'isDoAutoSelImmediate', isDoAutoSelImmediate);

			var pageType = [[${pageType}]];

			// 如果是模块编辑，则不需要自动拉单，否则将只显示拉单结果，而无法显示原来的数据
			if ("edit" == pageType) {
				if (isDoAutoSelImmediate) {
					doAutoSel[(${nestFormCode})](ajaxData);
				}
			}

			if(fields!='') { // 配置了条件,没有配置条件则不处理
				var sint = window.setInterval(function() { // 200毫秒检测一次
                    var newValueArr = getFormValue(fieldNames);
                    if (newValueArr != null) {
                        if(JSON.stringify(oldValueArr) != JSON.stringify(newValueArr)) {
                            console.log('oldValueArr', oldValueArr, 'newValueArr', newValueArr);
                            oldValueArr = newValueArr;
                            var ajaxData = {
                                'flowId': [[${flowId}]],
                                'parentFormCode': [[${parentFormCode}]],
                                'parentId': jQuery("[code='[(${nestFieldName})]']").attr('cwsId'),
                                'nestFieldName': [[${nestFieldName}]],
                                'isFirst':false
                            };
                            var isAllEmpty = true;
                            for (var i in fieldNames) {
                                ajaxData[fieldNames[i]] = newValueArr[i];
                                if (newValueArr[i]) {
                                    isAllEmpty = false;
                                }
                            }
                            // 如果全部参数都为空，则不能自动拉单
                            if (!isAllEmpty) {
                                doAutoSel[(${nestFormCode})](ajaxData);
                            }
                        }
                    }
				}, 100);
			}
		}
	}

    $(function() {
        initNestSheetAutoSel[(${nestFormCode})]();
    })

	async function doAutoSel[(${nestFormCode})](ajaxData) {
        $.ajax({
            async: false,
            type: "post",
            url: "../../nestsheetctl/autoSel",
            contentType: "application/x-www-form-urlencoded; charset=iso8859-1",
            data: ajaxData,
            dataType: "json",
            beforeSend: function (XMLHttpRequest) {
                // $('body').showLoading();
            },
            success: function (data, status) {
                console.log('autoSel data', data);
                if (data.ret == '1') {
                    var newIds = data.newIds || '';
                    if (newIds != '') {
                        mui.toast('自动拉单成功');
                    }

                    /*
                    var flowId = [(${flowId})];
                    if (flowId == -1) {
                        if (newIds!="") {
                            // 清除之前拉单的结果，因为有可能是更改了条件字段的值，重新拉单
                            $("input[name='tempCwsId_[(${nestFormCode})]']").remove();

                            var idsAry = newIds.split(",");
                            for (x in idsAry) {
                                addTempCwsId("[(${nestFormCode})]", idsAry[x]);
                            }
                        }
                    }*/
                }
            },
            complete: function (XMLHttpRequest, status) {
                // $('body').hideLoading();
            },
            error: function (XMLHttpRequest, textStatus) {
                // 请求出错处理
                alert(XMLHttpRequest.responseText);
            }
        });
	}

	// 获取主表单中的值并拼接成sql的where字句
	function getFormValue(fieldNames){
		var arr = new Array();
		for(var i = 0;i < fieldNames.length;i++) {
			var obj = o(fieldNames[i]);
			if (obj) {
				arr[i] = obj.value;
			} else {
				console.warn('getFormValue 表单中未找到: ' + fieldNames[i]);
				return null;
			}
		}
		return arr;
	}
</script>
</body>
</html>